<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--店员数据-->
      <el-col :span="24" :xs="24">
        <!-- 搜索条件 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="店员名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入店员名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="店员昵称" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入店员昵称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="审核状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="店员审核状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.app_service_audit_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核类型" prop="applyType">
            <el-select
              v-model="queryParams.applyType"
              placeholder="店员审核状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in applyTypeList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="店铺ID" prop="shopId" v-if="$store.getters && $store.getters.admin">
              <el-input
                v-model="queryParams.shopId"
                placeholder="请输入店铺ID"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作按钮组 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['employee:user:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['employee:user:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['employee:user:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格数据 -->
        <template>
          <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column type="index" label="序号" width="50" align="center" />
            <!-- <el-table-column label="ID" align="center" key="userId" prop="userId" /> -->
            <el-table-column label="店员" align="center" key="nickName" width="150" >
              <template slot-scope="scope">
                <div class="flex-align-center">
                  <el-avatar shape="circle" size="medium" :src="scope.row.avatar" alt="404"></el-avatar>
                  <div class="mgl5 font-14">{{scope.row.nickName}}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="性别" align="center" key="sex" prop="sex">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
              </template>
            </el-table-column>
            <el-table-column label="审核状态" align="center" key="status" prop="status">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.app_service_audit_status" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="审核类型" align="center" key="applyType" prop="applyType">
              <template slot-scope="scope">
                <span>{{ COMMONFUNC.getLabelByKey(applyTypeList, scope.row.applyType) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="店铺名称" prop="shopInfo.shopName" v-if="$store.getters && $store.getters.admin" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable="custom" :sort-orders="['descending', 'ascending']">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="160"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['employee:user:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['employee:user:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </template>
      </el-col>
    </el-row>

    <!-- 添加或修改店员配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="height:600px; overflow-y: scroll;">
        <el-row>
          <el-col :span="8">
            <el-form-item label="店员昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入店员昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="店员头像" prop="avatar">
              <ImageUpload v-model="form.avatar" :limit="1" :file-size="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.applyType === 'add'">
          <el-col :span="8">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
              <div>(将作为登录账户)</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="微信号" prop="wxId">
              <el-input v-model="form.wxId" placeholder="请输入微信号" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="音视频" prop="speech">
              <FileUpload v-model="form.speech" :limit="1" :file-size="2" :fileType="['mp4', 'avi', 'rmvb', 'mov', 'hevc']" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.speech">
            <el-form-item label="预览">
              <video width="150" height="150" controls>
                <source :src="speechStr" type="video/mp4">
                您的浏览器不支持 video 标签。
              </video>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="店员相册" prop="images">
              <ImageUpload v-model="form.images" :file-size="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" v-if="form.applyType === 'add'">
            <el-form-item label="店员性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.applyType === 'add'">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="form.birthday" value-format="yyyy-MM-dd" type="date" placeholder="选择日期时间" style="width: 230px"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地区编码" prop="addressCode">
              <el-cascader v-model="form.addressCode" :options="areaList" placeholder="地区编码" maxlength="20" style="width: 230px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" v-if="form.applyType === 'add'">
            <el-form-item label="店员等级" prop="userLevel">
              <el-select v-model="form.userLevel" placeholder="请选择店员等级">
                <el-option
                  v-for="dict in levelList"
                  :key="dict.levelId"
                  :label="dict.levelTitle"
                  :value="dict.levelId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="激活状态" prop="active">
              <el-radio-group v-model="form.active">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务项目" prop="serviceType">
              <el-checkbox v-model="projectExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
              <el-checkbox v-model="projectNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
              <el-checkbox v-model="form.projectCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
              <el-tree
                class="tree-border"
                :data="projectOptions"
                show-checkbox
                default-expand-all
                ref="projectRefs"
                node-key="id"
                :check-strictly="!form.projectCheckStrictly"
                empty-text="加载中，请稍候"
                :props="defaultProps"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="店员标签" prop="tags">
              <el-select v-model="form.tags" multiple filterable allow-create
                default-first-option  placeholder="请选择店员标签，可创建条目" class="width-100">
                <el-option v-for="item in tagsList" 
                :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" prop="userProfile">
            <el-form-item label="自我介绍">
              <el-input v-model="form.userProfile" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm('approve')" v-if="form.status === 'audit'">通 过</el-button>
        <el-button type="danger" @click="submitForm('reject')" v-if="form.status === 'audit'">驳 回</el-button>
        <el-button type="primary" @click="submitForm('')">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, updateUserStatus, updateUser} from "@/api/employee/apply";
import { projectTreeSelect } from "@/api/market/project";
import { listLevel } from "@/api/market/level";
import addressData from "@/utils/area/area.js";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "EmployeeApply",
  dicts: ['sys_normal_disable', 'sys_user_sex',  'app_service_audit_status'],
  components: { },
  data() {
    var validateTreeProject = (rule, value, callback) => {
      let arr = this.$refs.projectRefs.getCheckedKeys(); // 在此获取选中的树形数据
      if (arr.length == 0 || !arr) {
        callback(new Error("请选择服务项目"));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店员表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 分组树选项
      deptOptions: undefined,
      projectExpand: true,
      projectNodeAll: false,
      // 服务项目
      projectOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 分组名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined,
        active: undefined,
        sex: undefined,
        userLevel: undefined,
        isRealName: undefined,
        autoOrder: undefined,
        shopId: undefined,
        deptId: undefined,
        orderByColumn: 'createTime',
        isAsc: 'descending',
      },
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "店员昵称不能为空", trigger: "blur" }
        ],
        userProfile: [
          { required: true, message: "店员介绍不能为空", trigger: "blur" }
        ],
        serviceType: [
          { required: true, validator: validateTreeProject, trigger: "change" }
        ],
        userLevel: [
          { required: true, message: "店员等级不能为空", trigger: "change" }
        ],
        active: [
          { required: true, message: "激活状态不能为空", trigger: "change" }
        ],
        tags: [
          { required: true, message: "店员标签不能为空", trigger: "blur" }
        ],
        birthday: [
          { required: true, message: "店员生日不能为空", trigger: "blur" }
        ],
        addressCode: [
          { required: true, message: "店员地区编码不能为空", trigger: "blur" }
        ],
        avatar: [
          { required: true, message: "店员头像不能为空", trigger: "blur" }
        ],
        images: [
          { required: true, message: "店员相册不能为空", trigger: "blur" }
        ],
        speech: [
          { required: true, message: "店员声音文件不能为空", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "店员声音文件不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      areaList:[],
      tagsList:[],
      levelList:[],
      applyTypeList: [
        { value: 'add', cssClass: '', listClass: '', label: '新增店员' },
        { value: 'edit', cssClass: '', listClass: '', label: '资料修改' },
      ],
      speechStr: '',
      baseUrl: process.env.VUE_APP_BASE_API,
      filePre: "http",
    };
  },
  watch: {
    'form.speech'(val){
      this.speechStr = val.indexOf(this.baseUrl) === -1 && val.indexOf(this.filePre) === -1 ? process.env.VUE_APP_BASE_API + val : val
    }
  },
  created() {
    this.areaList = addressData
    this.getList();
    this.getLevelList();
    this.getProjectTree();
  },
  mounted() {
  },
  methods: {
    /** 查询店员列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询等级列表 */
    getLevelList() {
      listLevel(this.addDateRange({ pageNum: 1, pageSize: 10000, orderByColumn: 'levelSort', isAsc: 'ascending',}, null)).then(response => {
        this.levelList = response.rows;
      });
    },
    /** 查询分组下拉树结构 - 服务类型 */
    getProjectTree() {
      projectTreeSelect().then(response => {
        this.projectOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        userName: undefined,
        phonenumber: undefined,
        wxId: undefined,
        serviceType: [],
        userLevel: undefined,
        active: "0",
        sex: undefined,
        status: "audit",
        remark: undefined,
        userProfile: undefined,
        projectCheckStrictly: true,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        this.form.serviceType = this.form.serviceType ? this.form.serviceType.split(",") : []
        this.form.addressCode = this.form.addressCode ? this.form.addressCode.split(",") : []
        this.form.tags = this.form.tags ? this.form.tags.split(",") : []
        this.form.active = "0";
        this.open = true;
        this.$nextTick(() => {
          this.$refs.projectRefs.setCheckedKeys(this.form.serviceType);
        });
        this.title = "修改店员";
      });
    },
    /** 提交按钮 */
    submitForm: function(status) {
      let content = this.form.applyType === 'add' ? '本操作将会新增一名店员，是否确认通过？' : this.form.applyType === 'edit' ? '确定通过修改，此操作会变更店员信息' : '内容错误'
      let tips = status === 'approve' ? content : status === 'reject' ? '是否驳回该用户的申请？' : '此操作仅保存数据'
      this.$modal.confirm(tips).then(function() {
      }).then(() => {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.serviceType = this.getProjectAllCheckedKeys();
            let params = JSON.parse(JSON.stringify(this.form))
            params.serviceType = params.serviceType && params.serviceType.length ? params.serviceType.join(',') : ''
            params.addressCode = params.addressCode && params.addressCode.length ? params.addressCode.join(',') : ''
            params.tags = params.tags && params.tags.length ? params.tags.join(',') : ''
            if(params.birthday){
              let b_a = params.birthday.split('-')
              params.constellation = this.getAstro(b_a[1], b_a[2])
            }
            if(status){
              params.status = status
              updateUserStatus(params).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.open = false;
                this.getList();
              });
            }else{
              updateUser(params).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          }else{
            this.$modal.msgError("信息有误，请查看是否填写正确");
          }
        });
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除店员编号为"' + userIds + '"的数据项？').then(function() {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('employee/apply/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    // 根据生日的月份和日期，计算星座。
    getAstro(m,d){
      let s = "摩羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手摩羯"; 
      let arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]; 
      let start = m * 2 - (d < arr[m - 1] ? 2 : 0); 
      return s.substring(start, start + 2) + "座"; 
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.projectOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.projectRefs.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.projectRefs.setCheckedNodes(value ? this.projectOptions: []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.form.projectCheckStrictly = value
    },
    // 所有服务项目节点数据
    getProjectAllCheckedKeys() {
      // 目前被选中的服务项目节点
      let checkedKeys = this.$refs.projectRefs.getCheckedKeys();
      // 半选中的服务项目节点
      let halfCheckedKeys = this.$refs.projectRefs.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
  }
};
</script>